package com.universityJob.modules.data.service.impl;


import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.universityJob.common.utils.*;
import com.universityJob.modules.data.dao.DataHistoryDao;
import com.universityJob.modules.data.dao.DataUserDao;
import com.universityJob.modules.data.entity.DataHistoryEntity;

import com.universityJob.modules.data.service.DataHistoryService;

import net.sf.json.JSONArray;
import org.apache.commons.collections.MapUtils;

import org.apache.commons.lang.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;


/**
 * @author mao on 2021/5/13.
 * @version 1.0 maozhijob@163.com
 */
@Service("historyService")
public class DataHistoryServiceImpl extends ServiceImpl<DataHistoryDao, DataHistoryEntity> implements DataHistoryService {
    @Autowired
    private Upload upload;
    @Autowired
    private ExportExcel exportExcel;
    @Autowired
    private FormatData formatData;
    @Autowired
    private DataHistoryDao dataHistoryDao;
    @Autowired
    private DataUserDao dataUserDao;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public R queryPage(Map<String, Object> params) {
        List<DataHistoryEntity> dataHistoryEntities = dataHistoryDao.selectAl(params);
        return R.ok().put("page",dataHistoryEntities);
    }


    @Override
    @Transactional
    public R saveHistory(DataHistoryEntity history) {
        if (StringUtils.isBlank(history.getContractor()) || StringUtils.isBlank(history.getContractedPosition())
                || StringUtils.isBlank(history.getContractedSalary()) || StringUtils.isBlank(history.getUsername())) {
            return R.error("所有信息都不能为空！");
        }
        history.setCreateTime(new Date());
        //sha256加密
        this.save(history);
        return R.ok();
    }

    @Override
    public R selectRecommends(Map<String, Object> params) {
        List<Map> maps = dataHistoryDao.selectRecommends(params);
        return R.ok().put("data",maps);
    }

    @Override
    public R statisticsJob() {
        Map map = dataHistoryDao.statisticsJob();
        return R.ok().put("data",map);
    }

    @Override
    public DataHistoryEntity findByid(Long historyId) {
        DataHistoryEntity dataHistoryEntity = dataHistoryDao.findById(historyId);
        return dataHistoryEntity;
    }

    @Override
    @Transactional
    public R update(DataHistoryEntity history) {
        if (StringUtils.isBlank(history.getContractor()) || StringUtils.isBlank(history.getContractedPosition())
                || StringUtils.isBlank(history.getContractedSalary()) || StringUtils.isBlank(history.getUsername())) {
            return R.error("所有信息都不能为空！");
        }
        this.updateById(history);
        return R.ok();
    }

    @Override
    public R deleteBatch(Long[] historyId) {
        boolean remove = this.removeByIds(Arrays.asList(historyId));
        if (remove) {
            return R.ok();
        }
        return R.error("删除出错，请联系管理员！");
    }


    @Override
    public int exportStatisticsReport(HttpServletResponse response, Map<String, Object> params) {
        //获取数据
        List<DataHistoryEntity> dataHistoryEntities = dataHistoryDao.selectAl(params);
        List<Map<String, Object>> maps = EntityConvertMap(dataHistoryEntities);
        for (Map m : maps) {
            String gender = formatData.formateSex(org.apache.commons.collections.MapUtils.getString(m, "gender", ""));
            m.put("gender", gender);
            String status = formatData.formateStatus(org.apache.commons.collections.MapUtils.getString(m, "status", ""));
            m.put("status", status);
        }
        int i = exportExcel.excelInit(maps, response, params);
        if (i == 0) {
            //excel导出失败！
            return 0;
        }
        //以上均为数据准备,下面开始调用导出excel工具类
        return 1;
    }

    @Override
    public int inputExcel(HttpServletResponse response, Map<String, Object> params) {
        String histories = MapUtils.getString(params, "history", "");
        int count = 0;
        JSONArray jsonArray = JSONArray.fromObject(histories);
        List<DataHistoryEntity> list = (List<DataHistoryEntity>) JSONArray.toCollection(jsonArray, DataHistoryEntity.class);
        for (DataHistoryEntity history : list) {
            try {

                    dataHistoryDao.insert(history);
                    count += 1;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return count;
    }
    //list实体类转换成map
    public static  List<Map<String,Object>> EntityConvertMap(List<DataHistoryEntity> list) {
        List<Map<String, Object>> l = new ArrayList<>();
        try {
            for (DataHistoryEntity t : list) {
                Map<String, Object> map = new HashMap<>();
                Method[] methods = t.getClass().getMethods();
                for (Method method : methods) {
                    if (method.getName().startsWith("get")) {
                        String name = method.getName().substring(3);
                        name = name.substring(0, 1).toLowerCase() + name.substring(1);
                        Object value = method.invoke(t);
                        map.put(name, value);
                    }
                }
                l.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l;
    }
}
